/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/

package edu.jxufe.nb112.common.security.shiro;

import edu.jxufe.nb112.common.code.security.mode.IUserAuth;
import edu.jxufe.nb112.common.security.service.SecurityService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

/**
 * Created by lvxi on 2017/2/7.
 */
public class Realm extends AuthorizingRealm{

    private SecurityService securityService;

    /**
     * 获取授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String account = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.addRole("root");

        return authorizationInfo;
    }

    /**
     * 获取身份认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String account = (String) authenticationToken.getPrincipal();
        if(StringUtils.isNotEmpty(account)){
            IUserAuth userAuth = securityService.findUserAuthByAccount(account);
            if(userAuth==null) {
                throw new UnknownAccountException();
            }
            UserAuthenticationInfo authenticationInfo = new UserAuthenticationInfo(
                    userAuth,
                    account, //用户名
                    userAuth.getPassword(), //密码
                    new ShiroSimpleByteSource(userAuth.getSalt()),
                    getName() //realm name
            );
            return authenticationInfo;
        }else {
            throw new UnknownAccountException();
        }
    }

    @Override
    protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
        if(principals instanceof  SimplePrincipalCollection){
            return  ((SimplePrincipalCollection)principals).toString();
        }
        return principals;
    }


    public SecurityService getSecurityService() {
        return securityService;
    }

    public void setSecurityService(SecurityService securityService) {
        this.securityService = securityService;
    }

}
